<template>
  <el-main>
    <div class="w-full flex flex-row gap-2 border-b-gray-300 border p-2">
      <el-input v-model="searchQuery" placeholder="动物名称" class="max-w-[200px]"></el-input>
      <el-select v-model="FilterType"  placeholder="种类" style="width: 200px"  v-if="USER.role==='3'||USER.role==='4'">
        <el-option
            v-for="item in TypeOptions"
            :key="item"
            :label="item"
            :value="item"
        />
      </el-select>
      <el-select v-if="USER.job!='医生'" v-model="FilterStatus" placeholder="处理状态" style="width: 200px" >
        <el-option
            v-for="item in statusoptions"
            :key="item.value"
            :label="item.label"
            :value="item.label"
        />
      </el-select>
      <div>
        <el-button type="success" @click="FilteranimalRecord">查询</el-button>
        <el-button type="danger" @click="FilterReset">重置</el-button>
      </div>
    </div>
    <el-table v-if="medicallist" :data="medicallist" style="width: 100%" >
      <el-table-column prop="medical.id" label="编号"  />
      <el-table-column prop="animal.name" label="名称" />
      <el-table-column prop="animal.type" label="类别"  />
      <el-table-column prop="animal.age" label="年龄"  />
      <el-table-column prop="animal.gender" label="性别"  />
      <el-table-column prop="animal.healthStatus" label="健康状态"  />
      <el-table-column prop="animal.nowWeight" label="当前体重"  />
      <el-table-column prop="keepername" label="饲养员"  />
      <el-table-column prop="doctorname" label="医生名称"  />
      <el-table-column prop="medical.applicationTitle" label="申请主题"  />
      <el-table-column label="当前状态"  >
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.medical.applicationStatus === '待处理'">{{scope.row.medical.applicationStatus}}</el-tag>
          <el-tag type="warning" v-if="scope.row.medical.applicationStatus === '处理中'">{{scope.row.medical.applicationStatus}}</el-tag>
          <el-tag type="success" v-if="scope.row.medical.applicationStatus === '已结束'">{{scope.row.medical.applicationStatus}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400" >
        <template #default="scope">
          <div class="flex flex-row gap-1 w-[1000px]" >
            <button v-if="scope.row.medical.applicationStatus !== '已结束'&& !scope.row.animal.endTime" class="bg-element-green text-white px-1 py-1 rounded-md hover:bg-element-hover-green"  @click="HandleEdit(scope.row)">编辑</button>
              <el-button v-if="scope.row.animal.endTime" type="info" disabled @click="">已封档</el-button>
            <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="你确认要删除吗？"
                @confirm="Remove(scope.row)"
                @cancel="cancelEvent">
              <template #reference>
                <button v-if="scope.row.medical.applicationStatus !== '已结束'&& !scope.row.animal.endTime" class="bg-red-500 text-white px-2.5 py-1 rounded-md hover:bg-red-600">删除</button>
              </template>
            </el-popconfirm>
          </div>
        </template>

        <!--                医生看到的按钮-->
        <template #default="scope"  v-if="USER.job==='医生'">
          <div class="flex flex-row gap-1 w-[1000px]" >
            <button class="bg-element-green text-white px-1 py-1 rounded-md hover:bg-element-hover-green"  @click="HandleMedicalAccept(scope.row)"  >查看详情</button>
          </div>
        </template>
      </el-table-column>
    </el-table>



    <!-- 编辑窗口-->
    <el-dialog v-model="isFlag.dialogVisbaleMedical"  title="编辑界面" width="500" center>
      <el-form >
        <el-form-item label="预约主题:" label-width="80px">
          <el-input v-model="currentMedical.applicationTitle" :disabled="isFlag.FromDoctors"></el-input>
        </el-form-item>
        <el-form-item label="具体描述:" label-width="80px">
          <el-input type="textarea" v-model="currentMedical.applicationDetail" :disabled="isFlag.FromDoctors":rows="10"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isFlag.dialogVisbaleMedical = false">退出</el-button>
            <el-button type="primary" @click="SaveEdit" >修改</el-button>

        </div>
      </template>
    </el-dialog>
      <!-- 医生看到的窗口窗口-->
      <el-dialog v-model="isFlag.FromDoctors"  title="处理界面" width="500" center>
          <el-form >
              <el-form-item label="预约主题:" label-width="80px">
                  <el-input v-model="currentMedical.applicationTitle" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="具体描述:" label-width="80px">
                  <el-input type="textarea" v-model="currentMedical.applicationDetail" :disabled="true"></el-input>
              </el-form-item>
          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button @click="isFlag.FromDoctors = false">退出</el-button>
                  <el-popconfirm
                          confirm-button-text="是"
                          cancel-button-text="否"
                          :icon="InfoFilled"
                          icon-color="#626AEF"
                          title="你确认要接受该预约嘛？"
                          @confirm="MedicalAcceptSave"
                          @cancel="cancelEvent">
                      <template #reference>
                          <el-button type="primary"  >接受预约</el-button>
                      </template>
                  </el-popconfirm>
              </div>
          </template>
      </el-dialog>
  </el-main>
</template>
<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";

const USER = JSON.parse(localStorage.getItem('user'));

const isFlag = reactive({
  dialogVisbaleMedical:false,
  FromDoctors:false,
})


const medicallist =ref([])
let currentMedical=reactive({
  applicationTitle:String,
  applicationDetail:String,
});
const filteredList=ref([])
const CurrentMedical=ref();
const searchQuery = ref();
const FilterStatus =ref();
const FilterType =ref();
const statusoptions = [
  {
    value:'待处理',
    label:'待处理',
  },
  {
    value:'处理中',
    label:'处理中',
  },

  {
    value:'已结束',
    label:'已结束',
  },
]
const TypeOptions = ref({})
function init(){
    if(USER.job==='医生'){
        axios.get('http://localhost:8080/medical/getlist')
            .then(request =>{
                console.log(request)
                medicallist.value = request.data

                medicallist.value=medicallist.value.filter(item =>item.medical.applicationStatus && item.medical.applicationStatus =='待处理')
                console.log(FilterType.value)

            })
    }else{
        axios.get('http://localhost:8080/medical/getlist/byuserid?id='+USER.id)
            .then(request =>{
                console.log(request)
                medicallist.value = request.data
            })
    }

  axios.get('http://localhost:8080/animal/gettype')
      .then(request =>{
        console.log(request.data)
        TypeOptions.value=request.data;
        console.log(TypeOptions)
      })
}
onMounted(()=>{
  init()
})
function HandleEdit(currentmedical){
  CurrentMedical.value=null;
  CurrentMedical.value=currentmedical;
  console.log(CurrentMedical.value.medical.applicationDetail)
  currentMedical.applicationTitle=CurrentMedical.value.medical.applicationTitle;
  currentMedical.applicationDetail=CurrentMedical.value.medical.applicationDetail;
  isFlag.dialogVisbaleMedical=true;
}

// 检查字符串是否包含特殊字符的函数
function checkSpecialCharacters(input: string): boolean {
    // 此处可以根据需要定义特殊字符的规则，例如只允许中英文和数字，不允许特殊符号等
    const pattern = /[!@#$%^&*()+\=\[\]{};':"\\|,.<>\/?~]/;
    return pattern.test(input);
}

// 显示错误信息的弹窗
function showErrorMessage(message: string) {
    ElMessageBox.alert(message, '提示', {
        confirmButtonText: '确定',
    });
}

// 表单验证函数，确保主题不为空且不包含特殊字符
function validateFormMedical(tmpAnimal): boolean {
    if (tmpAnimal.applicationTitle.trim() === '') {
        showErrorMessage('预约主题不能为空');
        return false;
    }
    if (checkSpecialCharacters(tmpAnimal.applicationTitle)) {
        showErrorMessage('预约主题不能包含特殊字符');
        return false;
    }
    return  true
}
function SaveEdit(){
    // 检查表单是否通过验证
    if (!validateFormMedical(currentMedical)) {
        return; // 如果表单验证不通过，直接返回，不继续保存操作
    }

  CurrentMedical.value.medical.applicationDetail=currentMedical.applicationDetail;
  CurrentMedical.value.medical.applicationTitle=currentMedical.applicationTitle;
  axios.post('http://localhost:8080/medical/update',CurrentMedical.value.medical)
      .then(request =>{
        console.log(request.data)
        if (request.data){
          ElMessage({
            message:'修改成功',
            type:'success'
          })
          isFlag.dialogVisbaleMedical=false;
          init();
        }
      })

}
function HandleMedicalAccept(currentmedical){
  CurrentMedical.value=null;
  CurrentMedical.value=currentmedical;
  console.log(CurrentMedical.value.medical.applicationDetail)
  currentMedical.applicationTitle=CurrentMedical.value.medical.applicationTitle;
  currentMedical.applicationDetail=CurrentMedical.value.medical.applicationDetail;
  isFlag.FromDoctors=true;

}
function MedicalAcceptSave(){
  console.log(CurrentMedical)
  CurrentMedical.value.medical.doctorId=USER.id;
  CurrentMedical.value.medical.applicationStatus="处理中";
  console.log(CurrentMedical.value.medical)
  axios.post('http://localhost:8080/medical/update',CurrentMedical.value.medical)
      .then(request =>{
        console.log(request.data)
        if (request.data){
          ElMessage({
            message:'预约成功',
            type:'success'
          })
          isFlag.dialogVisbaleMedical=false;
          init();
        }
      })

}
function FilteranimalRecord (){

  axios.get('http://localhost:8080/medical/getlist')
      .then(request =>{
        filteredList.value = request.data
        console.log(filteredList)
        if(FilterType.value!=null){
          filteredList.value=filteredList.value.filter(item =>item.animal.type && item.animal.type == FilterType.value)
          console.log(FilterType.value)
        }
        if(FilterStatus.value=="待处理"){
          filteredList.value=filteredList.value.filter(item =>item.medical.applicationStatus && item.medical.applicationStatus =='待处理')
        }
        if(FilterStatus.value=="处理中"){
          filteredList.value=filteredList.value.filter(item =>item.medical.applicationStatus && item.medical.applicationStatus =='处理中')
        }
        if(FilterStatus.value=="已结束"){
          filteredList.value=filteredList.value.filter(item =>item.medical.applicationStatus && item.medical.applicationStatus =='已结束')
        }
        if(searchQuery.value!=null){
          filteredList.value=filteredList.value.filter(item => {
            return item.animal.name.includes(searchQuery.value);
          });}
        medicallist.value=filteredList.value;
      })
}
function Remove(currentMedical){
  axios.post('http://localhost:8080/medical/remove',currentMedical.medical)
      .then(request =>{
        console.log(request.data)
        if (request.data){
          ElMessage({
            message:'删除成功',
            type:'success'
          })
          location.reload()
        }
      })
}
function FilterReset(){
  location.reload();
}

</script>
